package com.symone.webcms.controller.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.symone.webcms.controller.base.BaseController;
import com.symone.webcms.model.*;
import com.symone.webcms.service.*;
import io.swagger.annotations.ApiImplicitParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cms/data")
public class DataController extends BaseController {

    @Autowired
    private ModuleService moduleService;
    @Autowired
    private ModuleFieldService fieldService;
    @Autowired
    private SiteNavService navService;
    @Autowired
    private DataPageService dataPageService;
    @Autowired
    private DataContentService dataContentService;
    @Autowired
    private DataExtService dataExtService;
    @Autowired
    private DataGroupService dataGroupService;

    @RequestMapping(value = "/sitenav/index", method = RequestMethod.GET)
    public ModelAndView navIndex() {
        ModelAndView mv = new ModelAndView();
        List<SiteNav> navs = navService.getNavTree(getSessionLanguage().getCode());
        mv.setViewName("/data/nav/index");
        mv.addObject("navs",navs);
        return mv;
    }

    @RequestMapping(value = "/sitenav/add", method = RequestMethod.GET)
    public ModelAndView navAdd() {
        List<SiteNav> navs = navService.selectList(new EntityWrapper<SiteNav>().where("deleted=0 and pid=0"));
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/nav/form");
        mv.addObject("navs",navs);
        mv.addObject("lang",getSessionLanguage().getCode());
        mv.addObject("nav",new SiteNav());
        return mv;
    }

    @RequestMapping(value = "/sitenav/edit", method = RequestMethod.GET)
    public ModelAndView navEdit(Long id) {
        List<SiteNav> navs = navService.selectList(new EntityWrapper<SiteNav>().where("deleted=0 and pid=0"));
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/nav/form");
        mv.addObject("navs",navs);
        mv.addObject("lang",getSessionLanguage().getCode());
        mv.addObject("nav",navService.selectById(id));
        return mv;
    }

    @RequestMapping(value = "/page/index", method = RequestMethod.GET)
    public ModelAndView pageIndex() {
        List<Module> modules = moduleService.selectList(new EntityWrapper<Module>().eq("type",1).and().eq("deleted",0).orderBy("createTime",true));
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/page/index");
        mv.addObject("modules", modules);
        mv.addObject("addAction",checkPermission("data:page:add"));
        mv.addObject("editAction",checkPermission("data:page:edit"));
        mv.addObject("removeAction",checkPermission("data:page:remove"));
        return mv;
    }

    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public ModelAndView pageAdd(String code) {
        Module module = moduleService.selectOne(new EntityWrapper<Module>().eq("deleted",0).and().eq("code",code).and().eq("type",1));
        List<ModuleField> fields = fieldService.selectList(new EntityWrapper<ModuleField>().eq("deleted",0).and().eq("module",code));
        Map<String,String> contentExtMap = new HashMap<>();
        DataPage dataPage = new DataPage();
        dataPage.setLang(getSessionLanguage().getCode());
        dataPage.setModule(code);

        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/page/form");
        mv.addObject("content",dataPage);
        mv.addObject("module", module);
        mv.addObject("fields", fields);
        mv.addObject("valmap",contentExtMap);
        return mv;
    }

    @RequestMapping(value = "/page/edit", method = RequestMethod.GET)
    public ModelAndView pageEdit(Long id) {
        DataPage dataPage = dataPageService.selectById(id);
        Module module = moduleService.selectOne(new EntityWrapper<Module>().eq("deleted",0).and().eq("code",dataPage.getModule()).and().eq("type",1));
        Wrapper<ModuleField> fieldWrapper = new EntityWrapper<ModuleField>()
                .where("deleted = 0 and module='"+ dataPage.getModule() +"'")
                .orderBy("sorting asc");
        List<ModuleField> fields = fieldService.selectList(fieldWrapper);

        Wrapper<DataExt> contentExtWrapper = new EntityWrapper<DataExt>()
                .eq("cid",id)
                .and()
                .eq("lang",dataPage.getLang())
                .and()
                .eq("module",dataPage.getModule());
        List<DataExt> contentExtList= dataExtService.selectList(contentExtWrapper);

        Map<String,String> contentExtMap = new HashMap<>();
        for (DataExt ce : contentExtList){
            contentExtMap.put(ce.getExtName(),ce.getExtValue());
        }

        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/page/form");
        mv.addObject("content",dataPage);
        mv.addObject("module", module);
        mv.addObject("fields",fields);
        mv.addObject("valmap",contentExtMap);
        return mv;
    }

    @RequestMapping(value = "/content/index", method = RequestMethod.GET)
    @ApiImplicitParam(name="code",value="模型CODE",required=true)
    public ModelAndView contentIndex(String code) {
        Module module = moduleService.selectOne(new EntityWrapper<Module>().eq("deleted",0).and().eq("code",code).and().eq("type",2));
        List<ModuleField> fields = fieldService.selectList(
                new EntityWrapper<ModuleField>()
                        .eq("module",code)
                        .and()
                        .eq("deleted",0)
                        .orderBy("sorting",true)
        );

        List<DataGroup> groups = dataGroupService.selectList(new EntityWrapper<DataGroup>()
                .eq("lang",getSessionLanguage().getCode())
                .and()
                .eq("module",code)
                .and()
                .eq("deleted",0)
        );

        List<ModuleField> listedFields = new ArrayList<>();
        List<ModuleField> searchedFields = new ArrayList<>();
        for (ModuleField field : fields){
            if(field.getListed() == 1){
                listedFields.add(field);
            }
            if(field.getSearched() == 1){
                searchedFields.add(field);
            }
        }

        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/content/index");
        mv.addObject("module", module);
        mv.addObject("groups", groups);
        mv.addObject("searchedFields", searchedFields);
        mv.addObject("cols", showColumns(listedFields));
        mv.addObject("addAction",checkPermission("data:content:" + code + ":add"));
        mv.addObject("editAction",checkPermission("data:content:" + code + ":edit"));
        mv.addObject("removeAction",checkPermission("data:content:" + code + ":remove"));
        return mv;
    }

    @RequestMapping(value = "/content/add", method = RequestMethod.GET)
    public ModelAndView contentAdd(String code) {
        Module module = moduleService.selectOne(new EntityWrapper<Module>().eq("deleted",0).and().eq("code",code).and().eq("type",2));
        List<ModuleField> fields = fieldService.selectList(new EntityWrapper<ModuleField>().eq("deleted",0).and().eq("module",code));
        Map<String,String> contentExtMap = new HashMap<>();
        DataContent dataContent = new DataContent();
        dataContent.setLang(getSessionLanguage().getCode());
        dataContent.setModule(code);

        List<DataGroup> groups = dataGroupService.selectList(new EntityWrapper<DataGroup>()
                .eq("lang",getSessionLanguage().getCode())
                .and()
                .eq("module",code)
                .and()
                .eq("deleted",0)
        );

        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/content/form");
        mv.addObject("groups", groups);
        mv.addObject("content",dataContent);
        mv.addObject("module", module);
        mv.addObject("fields", fields);
        mv.addObject("valmap",contentExtMap);
        return mv;
    }

    @RequestMapping(value = "/content/edit", method = RequestMethod.GET)
    public ModelAndView contentEdit(Long id) {
        DataContent dataContent = dataContentService.selectById(id);
        Module module = moduleService.selectOne(new EntityWrapper<Module>().eq("deleted",0).and().eq("code",dataContent.getModule()).and().eq("type",2));
        Wrapper<ModuleField> fieldWrapper = new EntityWrapper<ModuleField>()
                .where("deleted = 0 and module='"+ dataContent.getModule() +"'")
                .orderBy("sorting asc");
        List<ModuleField> fields = fieldService.selectList(fieldWrapper);

        Wrapper<DataExt> contentExtWrapper = new EntityWrapper<DataExt>()
                .eq("cid",id)
                .and()
                .eq("lang",dataContent.getLang())
                .and()
                .eq("module",dataContent.getModule());
        List<DataExt> contentExtList= dataExtService.selectList(contentExtWrapper);

        List<DataGroup> groups = dataGroupService.selectList(new EntityWrapper<DataGroup>()
                .eq("lang",getSessionLanguage().getCode())
                .and()
                .eq("module",dataContent.getModule())
                .and()
                .eq("deleted",0)
        );


        Map<String,String> contentExtMap = new HashMap<>();
        for (DataExt ce : contentExtList){
            contentExtMap.put(ce.getExtName(),ce.getExtValue());
        }

        ModelAndView mv = new ModelAndView();
        mv.setViewName("/data/content/form");
        mv.addObject("groups", groups);
        mv.addObject("content",dataContent);
        mv.addObject("module", module);
        mv.addObject("fields",fields);
        mv.addObject("valmap",contentExtMap);
        return mv;
    }

    private String showColumns(List<ModuleField> fields){
        String cols = "[[";
        cols += "{";
        cols += "'field':'id',";
        cols += "'width':'60',";
        cols += "'title':'ID'";
        cols += "},";
        cols += "{";
        cols += "'field':'group_name',";
        cols += "'width':'120',";
        cols += "'sort':true,";
        cols += "'title':'分组名'";
        cols += "},";
        for (ModuleField field : fields){
            cols += "{";
            cols += "'field':'" + field.getName() + "',";
            cols += "'title':'" + field.getTitle() + "',";
            if(field.getListWidth() > 0){
                cols += "'width':'" + field.getListWidth() + "',";
            }
            cols += "'sort':true,";
            cols = cols.substring(0,cols.length()-1);
            cols += "},";
        }
        cols += "{";
        cols += "'field':'state',";
        cols += "'title':'状态',";
        cols += "'width':'80',";
        cols += "'fixed':'right',";
        cols += "'sort':true,";
        cols += "'unresize':true,";
        cols += "'templet':'#content-list-table-switch-state-tpl'";
        cols += "},";
        cols += "{";
        cols += "'width':'120',";
        cols += "'fixed':'right',";
        cols += "'align':'left',";
        cols += "'unresize':true,";
        cols += "'toolbar':'#content-list-table-operate-bar'";
        cols += "}";
        cols += "]]";
        return cols;
    }
}
